<!--
 * @Descripttion: 退款订单弹框
 * @version: v1.0.0
 * @Author: wang pingqi
 * @Date: 2021-04-27 09:27:01
 * @LastEditors: wang pingqi
 * @LastEditTime: 2022-05-26 11:41:25
-->
<template>
  <KiFormDialog
    :show.sync="form__.show"
    title="订单退款"
    v-model="formData"
    class="form-dialog"
    @close="reset"
    ref="formDialog"
  >
    <template #el-form v-if="form__.data">
      <!-- <div>form__={{ form__ }}</div> -->
      <h2>
        <span class="title">订单总额</span
        ><span>¥ {{ form__.data.totalAmount | $cent2yuan }}</span>
      </h2>
      <el-table :data="form__.data.nightInfoList" border>
        <el-table-column label="间夜日期" prop="nightDate" align="center" />
        <el-table-column label="单价" prop="sellPrice" align="center">
          <template slot-scope="{ row }">
            {{ row.sellPrice | $cent2yuan }}
          </template>
        </el-table-column>
        <el-table-column label="间数" prop="quantity" align="center" />
      </el-table>

      <div style="margin-bottom: 28px"></div>

      <el-form-item label="酒店联系人手机号：" prop="hotelEmergencyPhone">
        <el-input
          v-if="form__.data.hotelEmergencyPhone"
          :value="form__.data.hotelEmergencyPhone | formatTelphone"
          style="width: 60%"
          disabled
        />
      </el-form-item>

      <el-form-item
        label="酒店联系人手机验证码"
        prop="code"
        :verify="{ type: 'verifyCode' }"
      >
        <el-input v-model.trim="formData.code" style="width: 60%" clearable :placeholder="validatorNumberOk?'请正确输入手机验证码':'请先正确输入退款金额'"/>
        <el-button
          @click="sendCode"
          :disabled="countdown !== 60 || !validatorNumberOk"
          style="margin-left: 12px"
        >
          {{ countdown === 60 ? "发送验证码" : `${countdown}s后重试` }}
        </el-button>
      </el-form-item>

      <el-form-item
        label="退款金额："
        prop="refundMoney"
        :rules="validatorNumber()"
  
      >
        <el-input
          v-model.trim="formData.refundMoney"
          style="width: 60%"
          placeholder="请输入退款金额"
          clearable
        >
        <template slot="prepend">¥ </template>
        </el-input>
        <span class="tips">注：输入金额不能大于订单金额</span>
      </el-form-item>

      <el-form-item
        label="确认退款："
        prop="confirmRefund"
        :rules="validatorConfirmRefund()"
      >
        <el-input
          v-model.trim="formData.confirmRefund"
          style="width: 60%"
          :placeholder="`请输入&quot;${sureRefundText}&quot;`"
          clearable
        />
        <span class="tips" v-if="formData.confirmRefund == sureRefundText">
          当前仅支持全额退款
        </span>
      </el-form-item>
    </template>

    <div slot="footer" class="footer">
      <el-button @click="onCancel"> 取消 </el-button>
      <el-button type="primary" @click="onConfirm" :loading="form__.loading">
        确认退款
      </el-button>
    </div>
  </KiFormDialog>
</template>

<script>
export default {
  props: {
    form: {
      type: Object,
      required: true,
      default() {
        return {
          show: false,
          data: null,
          loading: false,
        };
      },
    },
  },
  data() {
    return {
      // 弹框对象
      form__: this.form,
      // 弹框表单对象
      formData: {},
      // 倒计时计数
      countdown: 60,
      // 定时器对象
      timer: null,
      sureRefundText: "确认对此笔订单进行退款",
      // ajax请求中
      ajaxLoading: false,
      // 退款金额验证成功标志
      validatorNumberOk: false,
    };
  },
  watch: {
    "form__.show": {
      handler(nv) {
        if (nv) {
          this.queryForDetail();
        }
      },
      immediate: true,
    },
  },
  filters: {
    formatTelphone(value) {
      //  return value.replace(value.substring(3,7), "****")
      return value.replace(/(\d{3})\d{4}(\d{4})/, "$1****$2");
    },
  },
  methods: {
    /**
     * 弹框关闭重置
     * @return Void
     */
    reset() {
      this.$refs.formDialog.$refs.elForm.clearValidate();
      if (this.timer) {
        clearInterval(this.timer);
      }
    },
    /**
     * 验证“退款金额”
     * @return Array
     */
    validatorNumber() {
      const self = this;
      return {
        validator: (rule, value, callback) => {
          self.validatorNumberOk = false;
          if (!value && value !== "0") {
            callback(new Error("必填项"));
            return false;
          }
          const res = /^(([1-9][0-9]*)|(([0]\.\d{1,2}|[1-9][0-9]*\.\d{1,2})))$/.test(value);
          if (!res) {
            callback(new Error("请正确输入值"));
            return false;
          }
          if (self.form__ && self.form__.data && self.form__.data.totalAmount) {
            if (
              res &&
              self.form__.data.totalAmount &&
              Number(value) > self.form__.data.totalAmount/100
            ) {
              callback(new Error("退款金额不能大于订单金额"));
              return false;
            }
          }
          self.validatorNumberOk = true;
          callback();
        },
        required : true,
        trigger: "change",
      };
    },
    /**
     * 验证“确认退款”
     * @return Array
     */
    validatorConfirmRefund() {
      return [
        {
          required: true,
          message: "必填项",
        },
        {
          validator: (rule, value, callback) => {
            if (value !== this.sureRefundText) {
              callback(new Error("请正确输入值"));
            }
            callback();
          },
          trigger: "blur",
        },
      ];
    },
    /**
     * 取消
     * @return Void
     */
    onCancel() {
      this.$set(this.form__, "show", false);
    },
    /**
     * 确认退款
     * @return Void
     */
    onConfirm() {
      if (this.form__.loading) {
        return false;
      }
      this.$refs.formDialog.$refs.elForm.validate((valid) => {
        if (valid) {
          this.$set(this.form__, "loading", true);
          const { code, refundMoney } = this.formData;
          this.$POST(`sot-admin-api/hotel/self-order/platformRefund`, {
            code,
            refundMoney : refundMoney*100,
            orderId: this.form.data.orderId,
          })
            .then(({ data }) => {
              this.$set(this.form__, "show", false);
            })
            .finally((_) => {
              this.$set(this.form__, "loading", false);
              this.$emit("change");
            });
        }
      });
    },
    /**
     * 点击发送验证码
     * @return Void
     */
    sendCode() {
      // 开始倒计时
      this.timer = setInterval(() => {
        this.countdown--;
        if (this.countdown <= 0) {
          clearInterval(this.timer);
          this.countdown = 60;
        }
      }, 1000);
      this.queryValidatorCode();
    },
    /**
     * 发送退款短信验证码
     * @return Void
     */
    queryValidatorCode() {
      if (this.ajaxLoading) {
        return false;
      }
      this.ajaxLoading = true;
      const { refundMoney } = this.formData;
      this.$POST("sot-admin-api/hotel/self-order/refundValidatorCode", {
        refundMoney : refundMoney*100,
        orderId: this.form.data.orderId,
      })
        .then(({ data }) => {
          this.$swal.success("短信验证码已发送");
        })
        .finally((_) => {
          this.ajaxLoading = false;
        });
    },
    /**
     * 获取订单详情数据
     * @return Void
     */
    queryForDetail() {
      this.$set(this.form__, "loading", true);
      this.$POST(`sot-admin-api/hotel/self-order/queryForDetail`, {
        id: this.form.data.orderId,
      })
        .then(({ data }) => {
          this.$set(this.form__, "data", data);
        })
        .finally((_) => {
          this.$set(this.form__, "loading", false);
        });
    },
  },
};
</script>

<style lang="scss" scoped>
.form-dialog {
  h2 {
    font-size: 18px;
    span {
      margin-right: 28px;
      &:last-child {
        color: #f00;
      }
    }
  }
  .tips {
    padding-left: 12px;
    color: #409eff;
  }
  .footer {
    text-align: center !important;
    padding-bottom: 18px !important;
  }
  .el-button {
    &.is-disabled {
      background: #eee;
      opacity: 0.48;
    }
  }
}
</style>
